package com.pkk.penguin.frame.know.boot.service.hbsl;

import static com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslClassContent.CLASS_CONTAINER;
import static com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslClassContent.CLASS_STUDY_COUNT;
import static com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslClassContent.CURRENT_COOKIE;
import static com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslClassContent.DEFAULT_STEP_TIME;
import static com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslClassContent.DEFAULT_STOP_NUM;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.pkk.penguin.frame.know.boot.bo.hbsl.MessageType;
import com.pkk.penguin.frame.know.boot.config.common.handle.AbstractWebSocketServer.WebScoketUtil;
import com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslClassContent;
import com.pkk.penguin.frame.know.boot.config.handle.hbsl.HbslWebSocketServer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @description: 华北水利的学习业务
 * @author: peikunkun
 * @create: 2020-05-13 15:15
 **/
@Slf4j
@Service
public class HbslStudyService {

  @Resource
  private HbslWebSocketServer hbslWebSocketServer;

  /**
   * @Description: 处理学习
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/5/13 0013 下午 5:07
   */
  public void handleStudy() {
    final Iterator<String> iterator = CLASS_CONTAINER.keySet().iterator();
    while (iterator.hasNext()) {
      final String classCode = iterator.next();
      if (CLASS_STUDY_COUNT.getOrDefault(classCode, new AtomicInteger(1)).get() > DEFAULT_STOP_NUM) {

        StringBuffer msg = new StringBuffer();
        msg.append("[").append(classCode).append("]-[").append(CLASS_CONTAINER.get(classCode))
            .append("]-第[").append(CLASS_STUDY_COUNT.getOrDefault(classCode, new AtomicInteger(1))).append("]次学习:学习结束");
        WebScoketUtil.broadcost(hbslWebSocketServer.getWebSocket(), MessageType.OPERATE, msg.toString());

        //清理数据
        CLASS_CONTAINER.remove(classCode);
        HbslClassContent.CLASS_STUDY_COUNT.remove(classCode);
        continue;
      }

      boolean result = this.handleClassStudy(classCode);
      if (result) {
        final AtomicInteger orDefault = CLASS_STUDY_COUNT.getOrDefault(classCode, new AtomicInteger(1));
        orDefault.addAndGet(1);
        HbslClassContent.CLASS_STUDY_COUNT.put(classCode, orDefault);
      }
    }
  }


  /**
   * @Description: 处理学习请求
   * @Param: classCode
   * @return: boolean
   * @Author: peikunkun
   * @Date: 2020/5/13 0013 下午 3:20
   */
  public boolean handleClassStudy(String classCode) {
    final String requestUrl = "http://ncwu.hnscen.cn/study/action-directory-CellLeaveLog";
    final HttpRequest post = HttpUtil.createPost(requestUrl);

    //设置请求头部分
    Map<String, String> headers = new HashMap<>();
    headers.put("Accept", "*/*");
    headers.put("Accept-Encoding", "gzip, deflate");
    headers.put("Accept-Language", "zh,zh-CN;q=0.9,zh-TW;q=0.8,en;q=0.7");
    headers.put("Connection", "keep-alive");
    headers.put("Content-Length", "105");
    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    headers.put("Cookie", CURRENT_COOKIE);
    headers.put("Host", "ncwu.hnscen.cn");
    headers.put("Origin", "http://ncwu.hnscen.cn");
    headers.put("Referer",
        "http://ncwu.hnscen.cn/study/directory.aspx?CourseOpenId=f97983f7-fcc6-4a00-b196-b6c24a1831fb&cellId=630327729gsagaa6q0k9kxnpaeaqe6a");
    headers.put("User-Agent",
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
    headers.put("X-Requested-With", "XMLHttpRequest");
    post.addHeaders(headers);

    //请求参数
    Map<String, Object> param = new HashMap<>();
    param.put("logId", classCode);
    param.put("cellLogId", classCode);
    param
        .put("videoEndTime", CLASS_STUDY_COUNT.getOrDefault(classCode, new AtomicInteger(1)).get() * DEFAULT_STEP_TIME);
    param.put("stopSconds", 0);
    param.put("isLeave", false);
    post.form(param);

    final HttpResponse execute = post.execute();
    final String body = execute.body();
    log.info("请求参数:{},请求结果:{}", classCode, body);

    final boolean success = "1".equals(JSONObject.parseObject(body).getString("code"));
    boolean isSuccess = (StringUtils.isNotBlank(body) || success);
    String r = isSuccess ? "学习成功" : "学习失败";
    StringBuffer msg = new StringBuffer();
    msg.append("【" + r + "】").append("[").append(classCode).append("]-[").append(CLASS_CONTAINER.get(classCode))
        .append("]-第[").append(CLASS_STUDY_COUNT.getOrDefault(classCode, new AtomicInteger(1)).get()).append("]次学习:::")
        .append(JSONObject.parseObject(body).getString("msg")).append("\n\n");
    WebScoketUtil.broadcost(hbslWebSocketServer.getWebSocket(), MessageType.OPERATE, msg.toString());
    if (StringUtils.isBlank(body)) {
      return false;
    }
    if ("1".equals(JSONObject.parseObject(body).getString("code"))) {
      return true;
    }
    return false;
  }
}
